# app/routes/auth.py
from flask import Blueprint, request, jsonify
from app import db
from app.services import AuthService  # 修改这里
from app.utils.security import hash_password, generate_jwt_token, token_required
from app.models import User, GuestUser
from app.utils.response_utils import (
    success_response,
    error_response,
    ResponseCode
)

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/getUserInfo', methods=['POST'])
@token_required
def get_user(currentUserId):
    data = request.get_json()
    userType = data.get('userType')
    """获取用户信息"""

    if not userType:
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message='缺少userType参数',
            http_code=400
        )

    # 这里可以添加权限检查，比如只能查看自己的信息或好友的信息
    if userType == 'normalUser':
        user = User.query.get(currentUserId)
        if not user:
            return error_response(code=ResponseCode.ACCOUNT_NOT_FOUND, message='账号不存在', http_code=405)
        return success_response(
            data={
                'user_id': user.user_id,
                'username': user.username,
                'status': user.status,
                'avatar_url': user.avatar_url,
                'actServer': user.actServer
            }
        )
    if userType == 'guestUser':
        guest = GuestUser.query.get(currentUserId)
        if not guest:
            return error_response(code=ResponseCode.ACCOUNT_NOT_FOUND, message='账号不存在', http_code=401)
        return success_response(
            data={
                'user_id': guest.guest_id,
                'username': '一名游客',
                'status': '',
                'avatar_url': '',
                'actServer': guest.actServer
            }
        )

@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')

    if not username or not password:
        return error_response(
            ResponseCode.PARAM_ERROR,
            '用户名和密码不能为空',
            400
        )

    result = AuthService.register_user(username, password, email)
    if result[1]>=400:  # 错误响应
        return error_response(
            code=ResponseCode.EMAIL_EXISTS,
            message=result[0]
        )

    user = result[0]

    return success_response(
        data={
            'user_id': user.user_id,
            'username': user.username
        },
        message='注册成功！'
    )


@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    email = data.get('email')
    password = data.get('password')

    if not email or not password:
        return error_response(
            ResponseCode.PARAM_ERROR,
            '用户名和密码不能为空',
            400
        )

    user = AuthService.authenticate_user(email, password)
    if not user:
        return error_response(
            ResponseCode.INVALID_CREDENTIALS,
            '用户名或密码错误',
            401
        )

    access_token = generate_jwt_token(user.user_id)

    return success_response(
        data={
            'access_token': access_token,
            'user_id': user.user_id,
            'username': user.username
        },
        message='登录成功'
    )


@auth_bp.route('/refresh', methods=['POST'])
def refresh():
    from flask_jwt_extended import get_jwt_identity
    current_user = get_jwt_identity()
    new_token = create_access_token(identity=current_user)
    return jsonify({'access_token': new_token}), 200


@auth_bp.route('/guest', methods=['POST'])
def create_guest():
    guest = AuthService.create_guest()

    if isinstance(guest, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PARAM_ERROR,
            message=guest[0],
            http_code=guest[1]
        )

    token = generate_jwt_token(guest.guest_id)
    return success_response(
        data={
            'guest_id': guest.guest_id,
            'session_token': token,
            'expires_at': guest.expires_at.isoformat()
        },
        message='游客登录成功'
    )

@auth_bp.route('/getCaptcha', methods=['GET'])
def get_captcha():
    import random
    import string
    # 定义字符集：数字+大写字母（因为不分大小写，所以只使用大写字母）
    characters = string.digits + string.ascii_uppercase
    # 随机选择4个字符
    captcha = ''.join(random.choice(characters) for _ in range(4))

    # 返回JSON格式的响应
    return success_response(
        message= 'success',
        data={
            'captcha': captcha
        }
    )

@auth_bp.route('/getPersonalInfo', methods=["POST"])
@token_required
def get_personal_info(currentUserId):
    data = request.get_json()
    user_id = data.get('user_id')
    if not user_id:
        return error_response(code=ResponseCode.PARAM_ERROR,message='参数错误',http_code=403)

    result = AuthService.get_personal_info(user_id=user_id)

    if isinstance(result, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PERMISSION_DENIED,
            message=result[0],
            http_code=result[1]
        )

    return success_response(
        data=result,
        message=f'success'
    )

@auth_bp.route('/editUserInfo', methods=["POST"])
@token_required
def edit_user_info(currentUserId):
    data = request.get_json()
    email = data.get('email')
    username = data.get('username')
    bio = data.get('bio')
    avatar_url = data.get('avatar_url')
    tags = data.get('tags')

    result = AuthService.edit_userInfo(user_id=currentUserId,username=username,
                                       email=email,bio=bio,avatar_url=avatar_url,
                                       tags=tags)

    if isinstance(result, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PERMISSION_DENIED,
            message=result[0],
            http_code=result[1]
        )

    return success_response(
        data=result,
        message=f'success'
    )